package com.heima.user.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.UserDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.CaptchaUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author nan
 * @since 2024-06-25
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    /**
     * 用户登录校验
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        Map<String, Object> map = new HashMap<>();
        String password = dto.getPassword();
        String phone = dto.getPhone();
        //判断是否是游客登录
        if (StringUtils.hasText(password) && StringUtils.hasText(phone)) {
            //查询用户信息
            ApUser user = lambdaQuery().eq(ApUser::getPhone, phone).one();
            if (user == null) {
                //用户名或密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_OR_PWD_ERROR);
            }
            //校验密码
            String pwd = MD5Utils.encode(password + user.getSalt());
            if (!user.getPassword().equals(pwd)) {
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_OR_PWD_ERROR);
            }
            user.setSalt("");
            user.setPassword("");
            map.put("user", user);
            map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
        } else {
            //游客登录
            map.put("user", 0);
            map.put("token", AppJwtUtil.getToken(0L));
        }
        return ResponseResult.okResult(map);
    }

    /**
     * 用户注册
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult register(UserDto dto) {

        ApUser user = new ApUser();
        BeanUtils.copyProperties(dto, user);
        String salt = CaptchaUtil.getCharacters();
        user.setSalt(salt);
        user.setPassword(MD5Utils.encode(user.getPassword() + salt));
        return ResponseResult.okResult(save(user));
    }
}
